//
//  UIImageView+Extension.swift
//  SwiftProject
//
//  Created by qindong on 2021/3/5.
//

import Foundation
import Kingfisher
import UIKit

let photoCache = KingfisherManager.shared.cache

extension UIImageView {
    //MARK: - UIImageView加载图片便捷方法 可设置回调
    func setAFImageWith(_ url : String, _ size : CGSize, _ placeholderImage : UIImage? = nil, _ completedBlock: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) {
        if url.isEmpty {
            image = placeholderImage
            return
        }
        var url : String = (url.removingPercentEncoding?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)!

        if url.contains("aliyuncs") {
            if size != .zero {
                url = url + "?x-oss-process=image/resize,w_\(Int(size.width * 2)),h_\(Int(size.height * 2))"
            }
            kf.setImage(with: URL(string: url)!, placeholder: placeholderImage, options: [.transition(.fade(0.5))], completionHandler: completedBlock)
        } else if size != .zero {
            let processor = DownsamplingImageProcessor(size: size.multipleSize(2))
            kf.setImage(with: URL(string: url)!, placeholder: placeholderImage, options: [.processor(processor), .transition(.fade(0.5))], completionHandler: completedBlock)
        } else {
            kf.setImage(with: URL(string: url)!, placeholder: placeholderImage, options: [.transition(.fade(0.5)),], completionHandler: completedBlock)
        }
    }
    
    //MARK: - 初始化imageView便捷构造器  支持渲染模式和图片方向调整
    convenience init(imageString : String, renderingMode : UIImage.RenderingMode = .alwaysOriginal, orientation : UIImage.Orientation = .up) {
        self.init(image: UIImage(named: imageString)?.withRenderingMode(renderingMode).qmui_image(with: orientation))
    }
    
//    //MARK: - 使用七牛云链接获取自定义尺寸图片
//    func setQiNiuImageWith(_ url : String, _ size : CGSize, _ placeholderImage : UIImage? = nil, _ completedBlock: ((AlamofireImage.AFIDataResponse<UIImage>) -> Void)? = nil) {
//        let imageUrl : String = url + "?imageView2/1/w/\(Int(size.width * 2))/h/\(Int(size.height * 2))"
//        setAFImageWith(imageUrl, size, placeholderImage, completedBlock)
//    }
    
    //MARK: - 使用阿里云链接获取自定义尺寸图片
//    func setAliImageWith(_ url : String, _ size : CGSize, _ placeholderImage : UIImage? = nil, _ completedBlock: ((AlamofireImage.AFIDataResponse<UIImage>) -> Void)? = nil) {
//        let imageUrl : String = url + "?x-oss-process=image/resize,w_\(Int(size.width * 2)),h_\(Int(size.height * 2))"
//        setAFImageWith(imageUrl, size, placeholderImage, completedBlock)
//    }
}
